include("HelloAudio.jl")
# using SampledSignals: SampleBuf

# x = sin.(2pi * (1:2S_num) * 440 / S_num)

dot_time = 0.1
blank_time = 0.1

dot = sound(440, dot_time)
splash = sound(440, 2blank_time + dot_time)
blank = 0 * sound(440, blank_time)

#= morse: '.' '-' =#

letter_to_morse = Dict(' ' => " ", 'A' => ".-", 'B' => "-...", 'C' => "-.-.",
    'D' => "-..", 'E' => ".", 'F' => "..-.", 'G' => "--.",
    'H' => "....", 'I' => "..", 'J' => ".---", 'K' => "-.-", 'L' => ".-..",
    'M' => "--", 'N' => "-.", 'O' => "---", 'P' => ".--.", 'Q' => "--.-",
    'R' => ".-.", 'S' => "...", 'T' => "-", 'U' => "..-", 'V' => "...-",
    'W' => ".--", 'X' => "-..-", 'Y' => "-.--", 'Z' => "--..",
    '1' => ".----", '2' => "..---", '3' => "...--", '4' => "....-", '5' => ".....", '6' => "-....",
    '7' => "--...", '8' => "---..", '9' => "----.", '0' => "-----")


function play_str(str)
    println("samplerate:$(S_num)Hz")
    println("morse: $(str_to_morse(str))")
    play_morse(str_to_morse(str))
end

function play_morse(str)
    # sum_buf = SampledSignals.SampleBuf(zeros(eltype(buf), 0), samplerate(buf))
    sum_data = []
    for key in str
        if key == '.'
            append!(sum_data, dot)
        elseif key == '-'
            append!(sum_data, splash)
        else
            append!(sum_data, blank)
        end
        append!(sum_data, blank)
    end
    buf = to_buf(sum_data)
    play(buf)
end

function str_to_morse(str, dict=letter_to_morse)
    # 初始化一个空的字符串，用于存放结果
    result_str = ""

    # 遍历输入字符串中的每个字符
    for char in str
        # 如果字符在字典中，则用字典的值替换；否则，保留原字符
        if char in keys(dict)
            result_str *= dict[char]
        else
            result_str *= char
        end
        result_str *= ' '
    end

    return result_str
end


function morse_to_buf(str)
    # sum_buf = SampledSignals.SampleBuf(zeros(eltype(buf), 0), samplerate(buf))
    sum_data = Float64[]
    for key in str
        if key == '.'
            append!(sum_data, dot)
        elseif key == '-'
            append!(sum_data, splash)
        else
            append!(sum_data, blank)
        end
        append!(sum_data, blank)
    end
    return to_buf(sum_data)
end